﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFromTools
{
    public partial class ModifyProjectFileForm : Form
    {
        public ModifyProjectFileForm()
        {
            InitializeComponent();
        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            var extensions = txtDescExt.Text.Split(';', ',', ' ', '，', '；', '、');
            HandleFile(extensions, txtDirectory.Text, txtFileNames);
        }


        public void HandleFile(string[] ext, string srcDirectory, TextBox txtBox)
        {
            string[] fileList = Directory.GetFileSystemEntries(srcDirectory);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                if (Directory.Exists(file))
                {
                    string pathName = Path.GetFileName(file).ToLower();
                    //if (pathName.ToLower() == "bin" || pathName.ToLower() == "obj" || pathName.ToLower() == "" || pathName.ToLower() == "")
                    if (ContainString(pathName.ToLower(), ".vs", "$tf", "bin", "obj", ".svn", "_svn", "packages"))
                    {
                        continue;//  ".nuget", 
                    }

                    HandleFile(ext, file, txtBox);
                }
                // 否则作为文件来处理
                else
                {
                    string fileExtension = GetFileExtension(file);
                    if (!String.IsNullOrEmpty(fileExtension) && ext.Contains(fileExtension))
                    {
                        ReplaceFile(file, txtFind.Text, txtReplace.Text);
                        if (txtBox != null)
                        {
                            WriteLine(txtBox, file);
                        }
                    }
                }
            }
        }

        private static void WriteLine(TextBox txtBox, String text)
        {
            txtBox.Focus();
            txtBox.AppendText(text + Environment.NewLine);
            txtBox.ScrollToCaret();
            System.Windows.Forms.Application.DoEvents();
        }

        public static bool ContainString(string s, params string[] stringSet)
        {
            bool ret = false;
            foreach (string element in stringSet)
            {
                if (element.Trim().ToLower() == s.ToLower())
                {
                    ret = true;
                    break;
                }
            }

            return ret;
        }
        public static string GetFileExtension(string fileName)
        {
            int length = fileName.Length;
            int startIndex = length;
            while (--startIndex >= 0)
            {
                char ch = fileName[startIndex];
                if (ch == '.')
                {
                    return fileName.Substring(startIndex, length - startIndex);
                }
                if (((ch == Path.DirectorySeparatorChar) || (ch == Path.AltDirectorySeparatorChar)) || (ch == Path.VolumeSeparatorChar))
                {
                    break;
                }
            }
            return string.Empty;
        }

        public void ReplaceFile(string filePath, string oldString, string newString)
        {
            //int counter = 0;
            //string line;

            //// Read the file and display it line by line.  
            //StreamReader file =  new StreamReader(filePath);

            //while ((line = file.ReadLine()) != null)
            //{
            //    System.Console.WriteLine(line);
            //    counter++;
            //}

            //file.Close();
            string[] lines = System.IO.File.ReadAllLines(filePath);
            //using (StreamWriter file = new StreamWriter(filePath, true))
            //{
            //    file.WriteLine("Fourth line");
            //}
            //// 查找
            //foreach (string line in lines)
            //{
            //    // 如果包含指定的字符串
            //    if (!String.IsNullOrEmpty(line) && line.Contains(oldString))
            //    {
            //        WriteLine(txtFileNames, filePath);
            //    }

            //}

            // 替换
            using (StreamWriter file = new StreamWriter(filePath))
            {
                foreach (string line in lines)
                {
                    // 如果包含指定的字符串
                    if (!String.IsNullOrEmpty(line) && line.Contains(oldString))
                    {
                        file.WriteLine(line.Replace(oldString, newString));
                    }
                    else
                    {
                        file.WriteLine(line);
                    }
                }
            }
        }
    }
}
